import { createApp, nextTick } from 'vue'
import xtxMessage from '@/golbalComponents/xtxMessage'

function fnMessage (options) {
  //创建一个根标签div
  const div = document.createElement('div')
//统一设置class方便排序
  div.setAttribute('class', 'message')
// 创建message组件实例对象
  const messageCom = createApp(xtxMessage, {
    type: 'success',
    text: 'Elsa',
    remove,
    ...options
  })
//将message组件挂载到div
  messageCom.mount(div)
//将div追加到body的最后面挂载
  document.body.appendChild(div)
  sortMessageDiv()

// 封装  获取所有的class类名的div  回调到下一次dom更新后排序
  function sortMessageDiv () {
    nextTick(() => {
      const allDiv = document.querySelectorAll('.message')
      for (let i = 0; i < allDiv.length; i++) {
        allDiv[i].querySelector('.xtx-message').style.marginTop = 80 * i + 'px'
      }
    })
  }

//  封装  移除 div标签和 卸载message组件
  function remove () {
    //卸载message的挂载
    messageCom.unmount(div)
    //移除div元素 不让dom树存在无用div
    document.body.removeChild(div)
    //  重新排序div
    sortMessageDiv()
  }
}

export default function message (options) {
  fnMessage(options)
}
//message的type数组
const msgTypes = ['error', 'success', 'warn']
msgTypes.forEach(v => {
  message[v] = function (options) {
    options.type = v
    fnMessage(options)
  }
})
